package com.pda.yuanjing.pages.fucode;

import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.R;
import com.pda.yuanjing.beanin.ScanfBeanIn;
import com.pda.yuanjing.beanout.FMBeanOut;
import com.pda.yuanjing.beanout.JDBeanNewOut;
import com.pda.yuanjing.boardcast.CustomReceiver;
import com.pda.yuanjing.boardcast.ScannerInterface;
import com.pda.yuanjing.tools.StringUtils;
import com.public_module.basemvp.activity.BaseActivity;
import com.public_module.config.ApiYJ;
import com.public_module.config.SetConfig;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;
import com.public_module.tools.VoiceUtils;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class FuCodeActivity extends BaseActivity<FuCodeModel, FuCodeView, FuCodePresent> implements FuCodeView {
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tvr)
    TextView tvr;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;
    @BindView(R.id.sws)
    Switch sws;
    @BindView(R.id.oet)
    EditText oet;
    @BindView(R.id.bt)
    Button bt;
    @BindView(R.id.tvq)
    TextView tvq;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.tvzm)
    TextView tvzm;
    private String TAG = "CodeResetActivity";
    ScannerInterface scanner;
    CustomReceiver customReceiver = null;
    VoiceUtils voiceUtils;
    boolean flag = true;
    JDBeanNewOut.DataBean jdBeanNewOut;
    CodeAdapter codeAdapter = null;
    String zm = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fucode);
        ButterKnife.bind(this);
        jdBeanNewOut = (JDBeanNewOut.DataBean) getIntent().getSerializableExtra(PDApp.process);
        tvTitle.setText("溯源副码");
        sws.setChecked(flag);
        sws.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                flag = isChecked;
            }
        });
        scanner = new ScannerInterface(this);
        scanner.setOutputMode(1);
        customReceiver = new CustomReceiver(
                new CustomReceiver.PListener1() {
                    @Override
                    public void setData(CustomReceiver.Dataa dataa) {
                    }
                },
                new CustomReceiver.PListener2() {
                    @Override
                    public void setText(String string) {
                        String ss = StringProcess.codeMat(string);
                        if (flag) {
                            fm(ss);
                        } else {
                            fmscanf( zm ,ss);
                        }
                    }
                });
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScannerInterface.RES_ACTION);
        registerReceiver(customReceiver, filter);
        voiceUtils = new VoiceUtils(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customReceiver != null) {
            unregisterReceiver(customReceiver);
        }
        if (scanner != null) {
            scanner.setOutputMode(0);
        }
    }

    @Override
    public FuCodeModel createModel() {
        return new FuFuCodeModelImpl(this);
    }

    @Override
    public FuCodeView createView() {
        return this;
    }

    @Override
    public FuCodePresent createPresenter() {
        return new FuCodePresent();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void tip(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvq.setText(str);
                voiceUtils.voiceWarn();
            }
        });
    }

    @Override
    public void tipSuccess(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                oet.setText("");
                flag = false;
                sws.setChecked(flag);
                tvq.setText(str);
            }
        });
    }

    @OnClick({R.id.iv_title_left, R.id.bt})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.bt:
                if (oet.getText().toString().equals("")) {
                    tvq.setText("数码长度不符");
                    voiceUtils.voiceWarn();
                    return;
                }
                if (flag) {
                    fm(oet.getText().toString());
                } else {
                    fmscanf( zm ,oet.getText().toString());
                }
                break;
        }
    }

    public void fm(String code) {
        try {
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            ScanfBeanIn scanfBeanIn = new ScanfBeanIn();
            scanfBeanIn.setAction("SY_GetCodeFuMa");
            scanfBeanIn.setCid(SharedPreferencesManger.getCid());
            scanfBeanIn.setUserID(SharedPreferencesManger.getUid());
            scanfBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            scanfBeanIn.setCode(code);
            scanfBeanIn.setProcessID(jdBeanNewOut.getProcessID());
            scanfBeanIn.setJieDianName(jdBeanNewOut.getJieDianName());
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(scanfBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            FMBeanOut fmBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), FMBeanOut.class);
                            if (fmBeanOut == null) {
                                return;
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (fmBeanOut.getErrcode() == 0) {
                                        zm = code;
                                        tvzm.setText("主码:"+code);
                                        codeAdapter = new CodeAdapter(FuCodeActivity.this, fmBeanOut.getData());
                                        listview.setAdapter(codeAdapter);
                                        flag= false;
                                        sws.setChecked(flag);
                                        oet.setText("");
                                    } else {
                                        tvq.setText(fmBeanOut.getErrmsg());
                                        voiceUtils.voiceWarn();
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }

    public void fmscanf(String zcode, String code) {
        try {
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            ScanfBeanIn scanfBeanIn = new ScanfBeanIn();
            scanfBeanIn.setAction("SY_UpdateCode_FuMa");
            scanfBeanIn.setCid(SharedPreferencesManger.getCid());
            scanfBeanIn.setUserID(SharedPreferencesManger.getUid());
            scanfBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            scanfBeanIn.setCode(zcode);
            scanfBeanIn.setCodeFuMa(code);
            scanfBeanIn.setProcessID(jdBeanNewOut.getProcessID());
            scanfBeanIn.setJieDianName(jdBeanNewOut.getJieDianName());
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(scanfBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            FMBeanOut fmBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), FMBeanOut.class);
                            if (fmBeanOut == null) {
                                return;
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (fmBeanOut.getErrcode() == 0) {
                                        codeAdapter = new CodeAdapter(FuCodeActivity.this, fmBeanOut.getData());
                                        listview.setAdapter(codeAdapter);
                                        oet.setText("");
                                        tvq.setText("副码绑定成功");
                                        flag= true;
                                        sws.setChecked(flag);
                                    } else {
                                        tvq.setText(fmBeanOut.getErrmsg());
                                        voiceUtils.voiceWarn();
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }
}
